﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using EFERP;
using DevExpress.XtraEditors.Controls;
using HRM.DICTIONARY.DAL;
using DevExpress.XtraTreeList.Nodes;
using DevExpress.XtraTreeList;

namespace HRM.DICTIONARY.UI
{
    public partial class xfrmTransfer : DevExpress.XtraEditors.XtraForm
    {
        private DataTable dt;
        private int m_Status = 0;
        hrm_branchEx currBranch;

        ICommon<hrm_branch> exebra;
        ICommon<hrm_department> exedep;
        ICommon<hrm_group> exegro;
        ICommon<hrm_employee> exeEmp;
        List<hrm_employee> lstEmployee;

        public xfrmTransfer()
        {
            InitializeComponent();
        }

        public xfrmTransfer(List<hrm_employee> lstEmployee, ICommon<hrm_branch> exebra, ICommon<hrm_department> exedep, ICommon<hrm_group> exegro, ICommon<hrm_employee> exeEmp)  
        {
            InitializeComponent();
            this.lstEmployee = lstEmployee;
            this.exebra = exebra;
            this.exedep = exedep;
            this.exegro = exegro;
            this.exeEmp = exeEmp;
            //InitDataHRMBranch();
            foreach (hrm_employee objEmp in lstEmployee)
            {
                try
                {
                    ImageListBoxItem item = new ImageListBoxItem 
                    {
                        Value = objEmp.firstname.ToString() + " " + objEmp.lastname.ToString() + " (" + objEmp.employeecode.ToString() + ")"
                    };
                    if (objEmp.sex == 1)
                    {
                        item.ImageIndex = 0;
                    }
                    else
                    {
                        item.ImageIndex = 1;
                    }
                    if (int.Parse(objEmp.status.ToString()) == 3)
                    {
                        item.Value = item.Value.ToString() + " - Đã nghỉ việc";
                        item.ImageIndex = 2;
                    }
                    this.imglistEmployee.Items.Add(item);
                }
                catch
                {
                }
            }
            treeList1.FocusedNodeChanged += treeList1_FocusedNodeChanged;
            treeList1.GetSelectImage += treeList1_GetSelectImage;

            treeList2.FocusedNodeChanged += treeList1_FocusedNodeChanged;
            treeList2.GetSelectImage += treeList1_GetSelectImage;

            LoadAllData();
        }

        private void btOK_Click(object sender, EventArgs e)
        {
            //if (this.glkBranch.EditValue == null)
            //{
            //    XtraMessageBox.Show("Hãy chọn chi nhánh làm việc cho các ứng viên được tuyển dụng!");
            //}
            //else
            //{
            //    hrm_branch currBranch = exebra.DbSet.Where(l => l.branchcode == glkBranch.EditValue.ToString()).SingleOrDefault();
            //    foreach (ImageListBoxItem item in this.imglistEmployee.Items)
            //    {
            //        try
            //        {
            //            string str = item.Value.ToString();
            //            char[] separator = new char[] { '(', ')' };
            //            string employeeCode = str.Split(separator)[1];
            //            bool KQ = false;
            //            hrm_employee objEmp = lstEmployee.Where(o => o.employeecode == employeeCode).SingleOrDefault();
            //            if (objEmp.status != 3)
            //            {
            //                objEmp.branchcode = this.glkBranch.EditValue.ToString();
            //                if ((this.glkDepartment.EditValue == null) || (this.glkDepartment.Text == ""))
            //                {
            //                    objEmp.departmentcode = DBNull.Value.ToString();
            //                }
            //                else
            //                {
            //                    objEmp.departmentcode = this.glkDepartment.EditValue.ToString();
            //                }
            //                if ((this.glkGroup.EditValue == null) || (this.glkGroup.Text == ""))
            //                {
            //                    objEmp.groupcode = DBNull.Value.ToString();
            //                }
            //                else
            //                {
            //                    objEmp.groupcode = this.glkGroup.EditValue.ToString();
            //                }
            //                if (this.cheIsChangeMinimumSalary.Checked)
            //                {
            //                    objEmp.minimumsalary = objEmp.hrm_branch.minimumsalary;
            //                    if (objEmp.payform == 0)
            //                    {
            //                        objEmp.basicsalary = decimal.Parse(objEmp.coefficientsalary.ToString()) * objEmp.minimumsalary;
            //                    }
            //                }
            //                KQ = exeEmp.Update(objEmp);
            //                if (KQ) KQ = StaticVariable.Save();
            //                if (KQ)
            //                {
            //                    XtraMessageBox.Show("Quá trình hoàn tất!");
            //                    this.DialogResult = System.Windows.Forms.DialogResult.OK;
            //                }
            //                else XtraMessageBox.Show("Quá trình thất bại!");
            //            }
            //        }
            //        catch (Exception)
            //        {
            //            XtraMessageBox.Show("Quá trình thất bại!");
            //            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            //        }
            //    }


            //}
        }
        private void btCancel_Click(object sender, EventArgs e)
        {
            base.Close();
        }
        private void imglistEmployee_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
            {
                this.imglistEmployee.Items.RemoveAt(this.imglistEmployee.SelectedIndex);
            }
        }
        
        #region TreeView GridLookUp
        private void LoadTreeList()
        {
            string m_CompanyName = "NTSC";

            this.dt = new DataTable();
            this.dt.Columns.Add("ID");
            this.dt.Columns.Add("Name");
            this.dt.Columns.Add("ParentID");
            this.dt.Columns.Add("Type");
            this.dt.Columns.Add("FactQuantity");
            this.dt.Columns.Add("Quantity");
            this.dt.Columns.Add("ImageIndex");
            try
            {
                List<hrm_branch> lstBranch = exebra.GetList();
                List<hrm_department> lstDepartment = exedep.GetList();
                List<hrm_group> lstGroup = exegro.GetList();

                //Nhân viên quản lý toàn bộ chi nhánh. (Chùm cuối)
                if (StaticVariable.UserLogin.management == 0)
                {
                    this.dt.Rows.Add(new object[] { "All", m_CompanyName, "NTSC Groups Com.", "Company", 0, 0, 0 });
                    int factQuantity = 0;
                    int quantity = 0;

                    foreach (hrm_branch objbra in lstBranch)
                    {
                        this.dt.Rows.Add(new object[] { objbra.branchcode.ToString(), objbra.branchname.ToString() + this.StringQuantity(objbra), "All", "Branch", int.Parse(objbra.factquantity.ToString()), int.Parse(objbra.quantity.ToString()), 1 });
                        factQuantity += int.Parse(objbra.factquantity.ToString());
                        quantity += int.Parse(objbra.quantity.ToString());

                        //Load All Department with this branchcode
                        var listDep = exedep.Where(n => n.branchcode == objbra.branchcode).ToList();

                        foreach (hrm_department objdep in listDep)
                        {
                            this.dt.Rows.Add(new object[] { objdep.departmentcode.ToString(), objdep.departmentname.ToString() + this.StringQuantity(objdep), objdep.branchcode.ToString(), "Department", int.Parse(objdep.factquantity.ToString()), int.Parse(objdep.quantity.ToString()), 2 });

                            //Load All Group with this departmentcode 
                            var listGro = exegro.DbSet.Where(m => m.departmentcode == objdep.departmentcode).ToList();
                            foreach (hrm_group objgro in listGro)
                            {
                                this.dt.Rows.Add(new object[] { objgro.groupcode.ToString(), objgro.groupname.ToString() + this.StringQuantity(objgro), objgro.departmentcode.ToString(), "Group", int.Parse(objgro.factquantity.ToString()), int.Parse(objgro.quantity.ToString()), 3 });
                            }
                        }
                    }
                    this.dt.Rows[0]["Name"] = this.dt.Rows[0]["Name"].ToString() + this.StringQuantity(factQuantity, quantity);
                    this.dt.Rows[0]["FactQuantity"] = factQuantity;
                    this.dt.Rows[0]["Quantity"] = quantity;
                }
                //Nhân viên đăng nhập trực thuộc chi nhánh.
                else if (StaticVariable.UserLogin.management == 1)
                {
                    var lstBranchLocal = lstBranch.Where(d => d.branchcode == StaticVariable.UserLogin.branchcode).ToList().SingleOrDefault();
                    this.dt.Rows.Add(new object[] { lstBranchLocal.branchcode, lstBranchLocal.branchname + this.StringQuantity(int.Parse(lstBranchLocal.factquantity.ToString()), int.Parse(lstBranchLocal.quantity.ToString())), "", "Branch", lstBranchLocal.factquantity, lstBranchLocal.quantity, 1 });

                    //Lấy phòng ban nhân viên bởi branchcode nhân viên này trực thuộc
                    var lstDepartmentLocal = lstDepartment.Where(i => i.branchcode == lstBranchLocal.branchcode).OrderBy(s => s.departmentcode).ToList();
                    foreach (hrm_department objdep in lstDepartmentLocal)
                    {
                        this.dt.Rows.Add(new object[] { objdep.departmentcode.ToString(), objdep.departmentname.ToString() + this.StringQuantity(objdep), objdep.branchcode, "Department", int.Parse(objdep.factquantity.ToString()), int.Parse(objdep.quantity.ToString()), 2 });

                        var lstGroupLocal = lstGroup.Where(m => m.departmentcode == objdep.departmentcode).OrderBy(e => e.groupcode).ToList();
                        foreach (hrm_group objgro in lstGroupLocal)
                        {
                            this.dt.Rows.Add(new object[] { objgro.groupcode.ToString(), objgro.groupname.ToString() + this.StringQuantity(objgro), objgro.departmentcode.ToString(), "Group", int.Parse(objgro.factquantity.ToString()), int.Parse(objgro.quantity.ToString()), 3 });
                        }
                    }
                }
                else if (StaticVariable.UserLogin.management == 2)
                {
                    var lstDepartmentLocal = lstDepartment.Where(d => d.departmentcode == StaticVariable.UserLogin.departmentcode).ToList().SingleOrDefault();
                    this.dt.Rows.Add(new object[] { lstDepartmentLocal.departmentcode, lstDepartmentLocal.departmentname + this.StringQuantity(int.Parse(lstDepartmentLocal.factquantity.ToString()), int.Parse(lstDepartmentLocal.quantity.ToString())), "", "Department", lstDepartmentLocal.factquantity, lstDepartmentLocal.quantity, 2 });

                    var lstGroupLocal = lstGroup.Where(m => m.departmentcode == lstDepartmentLocal.departmentcode).OrderBy(e => e.groupcode).ToList();
                    foreach (hrm_group objgro in lstGroupLocal)
                    {
                        this.dt.Rows.Add(new object[] { objgro.groupcode.ToString(), objgro.groupname.ToString() + this.StringQuantity(objgro), objgro.departmentcode, "Group", int.Parse(objgro.factquantity.ToString()), int.Parse(objgro.quantity.ToString()), 3 });
                    }
                }
                else
                {
                    var lstGroupLocal = lstGroup.Where(d => d.groupcode == StaticVariable.UserLogin.groupcode).ToList().SingleOrDefault();

                    this.dt.Rows.Add(new object[] { lstGroupLocal.groupcode, lstGroupLocal.groupname + this.StringQuantity(int.Parse(lstGroupLocal.factquantity.ToString()), int.Parse(lstGroupLocal.quantity.ToString())), "", "Group", lstGroupLocal.factquantity, lstGroupLocal.quantity, 3 });
                }
                this.glkOrganizationTo.Properties.DataSource = this.dt;
                this.glkOrganizationFrom.Properties.DataSource = this.dt;
                
                this.glkOrganizationTo.Properties.DisplayMember = "Name";
                this.glkOrganizationTo.Properties.ValueMember = "ID";

                this.glkOrganizationFrom.Properties.DisplayMember = "Name";
                this.glkOrganizationFrom.Properties.ValueMember = "ID";

                this.treeList1.ExpandAll();
                this.treeList2.ExpandAll();
            }
            catch
            {
            }
        }
        private string StringQuantity(hrm_branch obj)
        {
            if (((this.m_Status == 0) || (this.m_Status == 1)) || (this.m_Status == 3))
            {
                return (" (" + obj.quantity.ToString() + "/" + obj.factquantity.ToString() + ")");
            }
            if (this.m_Status == 2)
            {
                return (" (" + obj.quantity.ToString() + ")");
            }
            int num = int.Parse(obj.factquantity.ToString()) - int.Parse(obj.quantity.ToString());
            return (" (" + num.ToString() + ")");
        }
        private string StringQuantity(hrm_department obj)
        {
            if (((this.m_Status == 0) || (this.m_Status == 1)) || (this.m_Status == 3))
            {
                return (" (" + obj.quantity.ToString() + "/" + obj.factquantity.ToString() + ")");
            }
            if (this.m_Status == 2)
            {
                return (" (" + obj.quantity.ToString() + ")");
            }
            int num = int.Parse(obj.factquantity.ToString()) - int.Parse(obj.quantity.ToString());
            return (" (" + num.ToString() + ")");
        }
        private string StringQuantity(hrm_group obj)
        {
            if (((this.m_Status == 0) || (this.m_Status == 1)) || (this.m_Status == 3))
            {
                return (" (" + obj.quantity.ToString() + "/" + obj.factquantity.ToString() + ")");
            }
            if (this.m_Status == 2)
            {
                return (" (" + obj.quantity.ToString() + ")");
            }
            int num = int.Parse(obj.factquantity.ToString()) - int.Parse(obj.quantity.ToString());
            return (" (" + num.ToString() + ")");
        }
        private string StringQuantity(int FactQuantity, int Quantity)
        {
            if (((this.m_Status == 0) || (this.m_Status == 1)) || (this.m_Status == 3))
            {
                return (" (" + FactQuantity.ToString() + "/" + Quantity.ToString() + ")");
            }
            if (this.m_Status == 2)
            {
                return (" (" + FactQuantity.ToString() + ")");
            }
            int num = Quantity - FactQuantity;
            return (" (" + num.ToString() + ")");
        }
        private void treeList1_FocusedNodeChanged(object sender, DevExpress.XtraTreeList.FocusedNodeChangedEventArgs e)
        {
            TreeList treelist = (TreeList)sender;
            DataRowView dataRecordByNode = (DataRowView)treelist.GetDataRecordByNode(e.Node);
            this.currBranch = new hrm_branchEx();
            if (e.Node != null)
            {
                if (dataRecordByNode["Type"].ToString() == "Company")
                {
                    currBranch.Level = 0;
                    currBranch.Code = "";
                }
                else if (dataRecordByNode["Type"].ToString() == "Branch")
                {
                    currBranch.branchcode = dataRecordByNode["ID"].ToString();
                    currBranch.Code = dataRecordByNode["ID"].ToString();
                    currBranch.Level = 1;
                }
                else if (dataRecordByNode["Type"].ToString() == "Department")
                {
                    currBranch.DepartmentCode = dataRecordByNode["ID"].ToString();
                    currBranch.Code = dataRecordByNode["ID"].ToString();
                    currBranch.Level = 2;
                }
                else if (dataRecordByNode["Type"].ToString() == "Group")
                {
                    currBranch.GroupCode = dataRecordByNode["ID"].ToString();
                    currBranch.Code = dataRecordByNode["ID"].ToString();
                    currBranch.Level = 3;
                }
                else if (dataRecordByNode["Type"].ToString() == "Employee")
                {
                    currBranch.EmployeeCode = dataRecordByNode["ID"].ToString();
                    currBranch.Level = 4;
                }
            }
            treelist.SetFocusedNode(e.Node);
        }
        private void treeList1_GetSelectImage(object sender, DevExpress.XtraTreeList.GetSelectImageEventArgs e)
        {
            TreeList treelist = (TreeList)sender;
            DataRowView dataRecordByNode = (DataRowView)treelist.GetDataRecordByNode(e.Node);
            e.NodeImageIndex = int.Parse(dataRecordByNode["ImageIndex"].ToString());
        }
        public void LoadAllData()
        {
            LoadTreeList();
        }

        private void imglistEmployee_Click(object sender, EventArgs e)
        {
            try
            {
                ImageListBoxItem item = (ImageListBoxItem)imglistEmployee.SelectedItem;
                string Ma_TenNV = item.Value.ToString();
                int indexMaNV = Ma_TenNV.IndexOf("(");
                string MaNV = Ma_TenNV.Substring(indexMaNV + 1);
                MaNV = MaNV.Replace(")", "");
                hrm_employee currEmp = lstEmployee.Where(n => n.employeecode == MaNV).SingleOrDefault();
                if (currEmp == null)
                    return;
                else
                {

                }
            }
            catch
            {
            }
        }

        //public void SelectNodeByLevelCode(int Level, string Code)
        //{
        //    foreach (TreeListNode node in this.treeList1.Nodes)
        //    {
        //        if ((int.Parse(node.GetValue("ImageIndex").ToString()) == Level) && (node.GetValue("ID").ToString() == Code))
        //        {
        //            this.treeList1.SetFocusedNode(node);
        //            break;
        //        }
        //        foreach (TreeListNode node2 in node.Nodes)
        //        {
        //            if ((int.Parse(node2.GetValue("ImageIndex").ToString()) == Level) && (node2.GetValue("ID").ToString() == Code))
        //            {
        //                this.treeList1.SetFocusedNode(node2);
        //                break;
        //            }
        //            foreach (TreeListNode node3 in node2.Nodes)
        //            {
        //                if ((int.Parse(node3.GetValue("ImageIndex").ToString()) == Level) && (node3.GetValue("ID").ToString() == Code))
        //                {
        //                    this.treeList1.SetFocusedNode(node3);
        //                    break;
        //                }
        //                foreach (TreeListNode node4 in node3.Nodes)
        //                {
        //                    if ((int.Parse(node4.GetValue("ImageIndex").ToString()) == Level) && (node4.GetValue("ID").ToString() == Code))
        //                    {
        //                        this.treeList1.SetFocusedNode(node4);
        //                        break;
        //                    }
        //                }
        //            }
        //        }
        //    }
        //}
        //public void SetFocusedNode(string code)
        //{
        //    this.treeList1.SetFocusedNode(this.treeList1.FindNodeByFieldValue("ID", code));
        //}
        #endregion
    }
}